package com.shenma2009.demo;

import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * @author 军哥
 * @version 1.0
 * @description: DelayQueueExample
 * @date 2023/6/28 17:17
 */

public class DelayQueueExample {
    public static void main(String[] args) {
        DelayQueue<DelayedTask> delayQueue = new DelayQueue<>();

        // 添加延时任务到延时队列
        delayQueue.add(new DelayedTask("Task 1", 3000)); // 3秒后执行
        delayQueue.add(new DelayedTask("Task 2", 5000)); // 5秒后执行
        delayQueue.add(new DelayedTask("Task 3", 2000)); // 2秒后执行

        // 从延时队列中取出任务并执行
        while (!delayQueue.isEmpty()) {
            try {
                DelayedTask task = delayQueue.take();
                System.out.println("Executing task: " + task.getName());
                // 执行任务的逻辑
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    static class DelayedTask implements Delayed {
        private final String name;
        private final long executeTime;

        public DelayedTask(String name, long delayInMillis) {
            this.name = name;
            this.executeTime = System.currentTimeMillis() + delayInMillis;
        }

        public String getName() {
            return name;
        }

        @Override
        public long getDelay(TimeUnit unit) {
            long delayInMillis = executeTime - System.currentTimeMillis();
            return unit.convert(delayInMillis, TimeUnit.MILLISECONDS);
        }

        @Override
        public int compareTo(Delayed o) {
            long diff = this.executeTime - ((DelayedTask) o).executeTime;
            return Long.compare(diff, 0);
        }
    }
}
